package com.gy.spring.mvc.common.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.fastjson.JSON;
import com.gy.spring.mvc.common.tools.R;

/**
 * TODO 请求拦截器
 *
 * @author geYang
 * @date 2018-02-11
 */
public class MyInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        //URI = contextPath + servletPath
        String uri = request.getRequestURI();
        //全部路径
        String url = request.getRequestURL().toString();
        //servlet.xml中设置的path
        String contextPath = request.getContextPath();
        //具体接口路径
        String servletPath = request.getServletPath();
        //请求域名(IP)
        String serverName = request.getServerName();
        //请求端口号
        int serverPort = request.getServerPort();

        System.out.printf("uri: %s;\n"
                        + "url: %s;\n"
                        + "contextPath: %s;\n"
                        + "servletPath: %s;\n"
                        + "serverName: %s;\n"
                        + "serverPort: %s;\n",
                uri, url, contextPath, servletPath, serverName, serverPort);

        //项目编译文件绝对路径
        System.out.println(request.getSession().getServletContext().getRealPath("/"));

//		if(!servletPath.startsWith("/login")) {
//			Cookie[] cookies = request.getCookies();
//			if(cookies != null) {
//				for (Cookie cookie : cookies) {
//					System.out.println("cookieName="+cookie.getName()+", cookieValue="+cookie.getValue());
//					if(cookie.getName().equals("sso") && cookie.getValue().equals("geYang|geYang888888")) {
//						return true;
//					}
//				}
//			}
//		} else {
        return true;
//		}
//		response.getOutputStream().write(JSON.toJSONString(R.err(510, "验证失败")).getBytes("UTF-8"));
//		return false;
    }

}
